package com.cjhstudy.mall.service.impl;

import com.cjhstudy.mall.dao.ProductMapper;
import com.cjhstudy.mall.pojo.Product;
import com.cjhstudy.mall.service.ICategoryService;
import com.cjhstudy.mall.service.IProductService;
import com.cjhstudy.mall.vo.ProductDetailVo;
import com.cjhstudy.mall.vo.ProductVo;
import com.cjhstudy.mall.vo.ResponseVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.cjhstudy.mall.enums.ProductStatusEnum.DELETE;
import static com.cjhstudy.mall.enums.ProductStatusEnum.OFF_SALE;
import static com.cjhstudy.mall.enums.ResponseEnum.PRODUCT_OFF_SALE_OR_DELETE;

/**
 * @author: phil
 * @ProjectName: mall
 * @Date: 2021/12/9
 */
@Service
@Slf4j
public class ProductServiceImpl implements IProductService {

    @Autowired
    private ICategoryService categoryService;

    @Autowired
    private ProductMapper productMapper;

    @Override
    public ResponseVo<PageInfo> list(Integer categoryId, Integer pageNum, Integer pageSize) {
        Set<Integer> categoryIdSet = new HashSet<>();
        if (categoryId != null){
            categoryService.findSubCategoryId(categoryId,categoryIdSet);
            categoryIdSet.add(categoryId);
        }

        //插入分页控制
        PageHelper.startPage(pageNum,pageSize);
        List<Product> productList = productMapper.selectByCategoryIdSet(categoryIdSet);
        List<ProductVo> productVoList = productList.stream()
                .map(e -> {
                    ProductVo productVo = new ProductVo();
                    BeanUtils.copyProperties(e, productVo);
                    return productVo;
                })
                .collect(Collectors.toList());

        PageInfo pageInfo = new PageInfo<>(productList);
        pageInfo.setList(productVoList);

        return ResponseVo.success(pageInfo);
    }

    @Override
    public ResponseVo<ProductDetailVo> detail(Integer productId) {

        Product product = productMapper.selectByPrimaryKey(productId);//把所有的武平查出来

        //在判断的时候只对确定性的条件判断
        if (product.getStatus().equals(OFF_SALE.getCode()) || product.getStatus().equals(DELETE.getCode())){
           return ResponseVo.error(PRODUCT_OFF_SALE_OR_DELETE);
        }

        ProductDetailVo productDetailVo = new ProductDetailVo(); //创建一个ProductDetailVo出来
        BeanUtils.copyProperties(product,productDetailVo); //将数据库中查出来的赋值到新的productDetailVo中，返回
        //对库存进行敏感数据处理
        productDetailVo.setStock(product.getStock() > 100 ? 100 : product.getStock());
        return ResponseVo.success(productDetailVo);
     }
}
